<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane :label="`${this.$route.name}搜索`"> </el-tab-pane>
      <avue-form ref="form" :option="searchOption" v-model="queryParams">
        <template slot-scope="{ size }" slot="btn">
          <el-button type="primary" :size="size" class="el-icon-search" @click="handleSubmit">搜索</el-button>
          <el-button :size="size" @click="handleCancel" class="el-icon-delete">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="tab-font" style="margin-top: 24px">
      <el-tab-pane :label="`${this.$route.name}明细`" class="tab-font"> </el-tab-pane>
      <avue-crud
        :option="option"
        :data="data"
        :page.sync="page"
        :table-loading="loading"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
        </template>
      </avue-crud>
    </el-tabs>
  </basic-container>
</template>

<script>
import { getReportData, viewReportConfig, exportReportData } from '@/api/admin/reportConfig';
import { camelToUnderline, underlineToCamel } from '@/util/util';

export default {
  name: 'reportTemplate',
  data() {
    return {
      searchOption: {
        menuPosition: 'left',
        submitBtn: false,
        emptyBtn: false
      },
      option: {
        addBtn: false,
        filterBtn: false,
        columnBtn: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        menu: false
      },
      id: '',
      loading: false,
      queryParams: {},
      isPagenation: false,
      isDefaultLoad: false,
      data: [],
      page: { pageSize: 20, currentPage: 1, total: 0 }
    };
  },
  watch: {
    async $route(val) {
      await this.getIdFromRouter();
    }
  },
  async mounted() {
    await this.getIdFromRouter();
  },
  methods: {
    async onload() {
      try {
        this.loading = true;
        const params = this.getQueryParameter();
        const res = await getReportData(this.id, params);
        const data = res.data.data || [];
        this.data = data.records || [];
        this.page.pageSize = data.size;
        this.page.currentPage = data.current;
        this.page.total = data.total;
        // 获取数据
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    // format qeury 参数
    getQueryParameter() {
      const reportQueryList = [];
      const queryParams = { ...this.queryParams };
      for (const key in queryParams) {
        if (key && queryParams[key] && !key.includes('$'))
          reportQueryList.push({
            field: camelToUnderline(key),
            defaultValue: Array.isArray(queryParams[key]) ? queryParams[key].join('TO') : queryParams[key]
          });
      }
      const params = {
        reportQueryList,
        query: { current: this.page.currentPage, size: this.page.pageSize }
      };
      //是否有分页
      return params;
    },
    handleCancel() {
      this.page.currentPage = 1;
      this.$refs.form.resetForm();
      this.queryParams = {};
      this.onload();
    },
    handleSubmit(params, done) {
      this.page.currentPage = 1;
      this.onload();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onload();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onload();
    },
    refreshChange() {
      this.onload();
    },
    async getTableConfig(id) {
      try {
        const res = await viewReportConfig({ id });
        const data = res.data.data;
        this.isDefaultLoad = data.isDefaultLoad;
        //设置表格列名  fieldsKey 为了设置搜索的时候少遍历
        this.setColumn(data);
        //设置搜索条件  option.column
        this.setSearchCol(data);
        // 获取数据
      } catch (e) {
        console.warn(e);
      }
    },
    async getIdFromRouter() {
      const match = this.$route.path.match(/\d+/);
      if (match.input.includes('report/reportTemplate/')) {
        if (match) {
          const id = match[0];
          this.id = id;
          await this.getTableConfig(id);
          if (this.isDefaultLoad) {
            await this.onload();
          }
        } else {
          this.$message.error('请检查配置是否正确');
        }
      }
    },
    setColumn(data) {
      const optionJson = JSON.parse(data.optionJson);
      if (optionJson.pagination) {
        this.isPagenation = optionJson.pagination;
        this.page = { pageSize: 20, currentPage: 1, total: 0 };
      }
      const column = optionJson.columnDefs.map((item) => {
        return {
          label: item.headerName,
          prop: item.field,
          fixed: item.pinned,
          minWidth: item.minWidth || 150,
          type: item.type
        };
      });
      this.$set(this.option, 'column', column);
    },
    setSearchCol(data) {
      const componentMap = {
        text: 'input',
        number: 'number',
        select: 'select',
        date: 'date',
        datetimerange: 'datetimerange',
        daterange: 'daterange'
      };
      const column = [];
      data.reportQueryList.forEach((item) => {
        const type = item.controlType.toLowerCase();
        const columItem = {
          label: item.name,
          prop: item.field,
          span: 6,
          type: componentMap[type] || 'input'
        };

        if (componentMap[type] === 'datetimerange') {
          columItem.valueFormat = 'yyyy-MM-dd HH:mm:ss';
          columItem.format = 'yyyy-MM-dd HH:mm:ss';
        } else if (componentMap[type] === 'select') {
          columItem.dicData = JSON.parse(item.controlData);
          this.queryParams[item.field] = item.defaultValue;
        } else if (componentMap[type] === 'date') {
          columItem.valueFormat = 'yyyy-MM-dd';
          columItem.format = 'yyyy-MM-dd';
        } else if (componentMap[type] === 'daterange') {
          columItem.valueFormat = 'yyyy-MM-dd';
          columItem.format = 'yyyy-MM-dd';
        }
        column.push(columItem);
      });
      column.push({
        label: '',
        prop: 'btn',
        span: 6,
        formslot: true
      });
      this.$set(this.searchOption, 'column', column);
    },

    async handleExport() {
      const params = this.getQueryParameter();
      try {
        const res = await exportReportData(this.id, params);
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
        const fileName = `${this.$route.name}.xlsx`;
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        this.$message.error('系统错误，请联系管理员');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
